package com.cgt.common.utils;

import lombok.Data;

import static com.cgt.common.utils.ErrorInfo.Code.FAILED;
import static com.cgt.common.utils.ErrorInfo.Code.SUCCESS;
import static com.cgt.common.utils.ErrorInfo.Msg.OK;

@Data
public class R<T> {
    // 务状态码，20θ-成功，其它-失败
    private int code;
    // 响应消息 例如：OK
    private String msg;
    // 响应数据
    private T data;
    // 请求id
    private String requestId;

    public static R<Void> ok() {
        return new R<Void>(SUCCESS, OK, null);
    }

    public static <T> R<T> ok(T data) {
        return new R<>(SUCCESS, OK, data);
    }

    public static <T> R<T> ok(String msg, T data) {
        return new R<>(SUCCESS, msg, data);
    }

    public static <T> R<T> error(String msg) {
        return new R<>(FAILED, msg, null);
    }

    public static <T> R<T> error(int code, String msg) {
        return new R<>(code, msg, null);
    }

    public R() {
    }

    public R(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        // todo 设置请求id
    }

    public boolean success() {
        return code == SUCCESS;
    }

    public R<T> requestId(String requestId) {
        this.requestId = requestId;
        return this;
    }

    public static<T> R<T> fail(String msg) {
        return new R<>(FAILED, msg, null);
    }
}
